package com.zshield.util;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import com.zshield.config.KafkaConfig;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;

public class HealthMonitor {
    public static long ChangingTimeMillis = -1;
    private static final Logger logger = Logger.getLogger(HealthMonitor.class);

    public static void startServer(Thread thread) {
        HttpServer server = null;
        try {
            server = HttpServer.create(new InetSocketAddress(18000), 0);
        } catch (IOException e) {
            KafkaConfig.printErrorLog(logger,e);
        }
        server.createContext("/", new MyHandler(thread));
        server.setExecutor(null);
        server.start();
        logger.info("[kstream server start successfully]");
    }

    static class MyHandler implements HttpHandler {
        Thread thread ;
        public MyHandler(Thread thread) {
            this.thread = thread;
        }

        @Override
        public void handle(HttpExchange t) throws IOException {
            String response = "{\"status\":\"WAIT\"}";
            if (ChangingTimeMillis != -1) {
                long intervalMillis = System.currentTimeMillis() - HealthMonitor.ChangingTimeMillis;
                boolean heartbeat = intervalMillis < 10 * 1000;
                boolean alive = this.thread.isAlive();
                response = alive &&  heartbeat ? "{\"status\":\"OK\"}" : "{\"status\":\"ERROR\"}";
            }
            t.sendResponseHeaders(200, response.length());
            OutputStream outputStream = t.getResponseBody();
            outputStream.write(response.getBytes());
            outputStream.close();
        }
    }
}

